﻿// ***********************************************************************************************************************************************************
// * Copyright (c) 2008 Unit Software                                                                                                                        *
// *                                                                                                                                                         *
// * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),      *
// * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,      *
// * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:              *
// *                                                                                                                                                         *
// * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.                          *
// *                                                                                                                                                         *
// * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,     *
// * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER      *
// * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS    *
// * IN THE SOFTWARE.                                                                                                                                        *
// ***********************************************************************************************************************************************************
using System;
using System.Data;
using System.Data.Linq;
using System.Data.Linq.Mapping;

namespace UnitSoftware.LINQ2SQLExtensions
{
    public class ExtendedDataContext : DataContext
    {
        #region Public

        public event EventHandler<EntitiesEventArgs> OnEntitiesUpdated;
        public event EventHandler<EntitiesEventArgs> OnEntitiesDeleted;
        public event EventHandler<EntitiesEventArgs> OnEntitiesInserted;
        public event EventHandler<DataChangesEventArgs> OnSubmitChanges;
        public event EventHandler<DataChangesEventArgs> OnPreSubmitChanges;

        #region ctors

        public ExtendedDataContext(string fileOrServerConection)
            : base(fileOrServerConection)
        {
        }

        public ExtendedDataContext(IDbConnection connection, MappingSource mappingSource)
            : base(connection, mappingSource)
        {
        }

        public ExtendedDataContext(string fileOrServerConection, MappingSource mappingSource)
            : base(fileOrServerConection, mappingSource)
        {
        }

        public ExtendedDataContext(IDbConnection connection)
            : base(connection)
        {
        }

        #endregion

        public override void SubmitChanges(ConflictMode failureMode)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Applies default: ConflictMode.ContinueOnConflict
        /// </summary>
        public new DataChanges SubmitChanges()
        {
            var changeSet = GetChangeSet();

            var dataChanges = new DataChanges();

            if (changeSet.Updates.Count != 0 || changeSet.Inserts.Count != 0 || changeSet.Deletes.Count != 0)
            {
                dataChanges.Deletes.AddRange(changeSet.Deletes);
                dataChanges.Updates.AddRange(changeSet.Updates);
                dataChanges.Inserts.AddRange(changeSet.Inserts);

                try
                {
                    if (OnPreSubmitChanges != null && dataChanges.Deletes.Count > 0)
                        OnPreSubmitChanges(this, new DataChangesEventArgs(this, dataChanges));

                    base.SubmitChanges(ConflictMode.ContinueOnConflict);
                }
                catch (ChangeConflictException)
                {
                    dataChanges.Conflicts.AddRange(ChangeConflicts);

                    foreach (var conflict in ChangeConflicts)
                        dataChanges.Updates.Remove(conflict.Object);

                    if (OnEntitiesDeleted != null && dataChanges.Deletes.Count > 0)
                        OnEntitiesDeleted(this, new EntitiesEventArgs(dataChanges.Deletes, this));

                    if (OnEntitiesUpdated != null && dataChanges.Updates.Count > 0)
                        OnEntitiesUpdated(this, new EntitiesEventArgs(dataChanges.Updates, this));

                    if (OnEntitiesInserted != null && dataChanges.Inserts.Count > 0)
                        OnEntitiesInserted(this, new EntitiesEventArgs(dataChanges.Inserts, this));

                    if (OnSubmitChanges != null)
                        OnSubmitChanges(this, new DataChangesEventArgs(this, dataChanges));
                }
            }

            return dataChanges;
        }

        public DataChanges SubmitChangesAndResolveConflicts(RefreshMode refreshMode)
        {
            var totalDataChanges = new DataChanges();

            var dataChanges = SubmitChanges();

            totalDataChanges.AmalgamateExcludingConflicts(dataChanges);

            while (dataChanges.Conflicts.Count>0)
            {
                foreach (var conflict in dataChanges.Conflicts)
                    conflict.Resolve(refreshMode);

                dataChanges = SubmitChanges();

                totalDataChanges.AmalgamateExcludingConflicts(dataChanges);
            }

            return totalDataChanges;
        }
        
        #endregion
    }
}